<template>
  <div id="roles">
    <el-row class="table-grid-content">
      <el-col :span="6">
        <el-input v-model="input" placeholder="请输入关键字"></el-input>
      </el-col>
      <el-col :span="2" :offset="1">
        <el-button type="primary" icon="el-icon-plus" @click="addMenu()">增加角色</el-button>
      </el-col>
      <el-col :span="2" :offset="1">
        <el-button type="danger" icon="el-icon-delete" @click="batchDelMenus()">删除</el-button>
      </el-col>
      <el-col :span="2" style="margin-left: 14px;">
        <el-button @click="toggleSelection()" icon="el-icon-link">取消</el-button>
      </el-col>
    </el-row>
    <!-- 表格-->
    <el-table ref="multipleTable" :data="tables" tooltip-effect="dark" style="width: 100%"
      :row-class-name="tableRowClassName" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">

      </el-table-column>
      <el-table-column prop="rid" label="编号" width="140">

      </el-table-column>
      <el-table-column prop="rname" label="角色名称" width="150">
      </el-table-column>
      <el-table-column prop="code" label="角色代号" width="160"></el-table-column>
      <el-table-column prop="description" label="角色描述" width="160"></el-table-column>


      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)" round>修改</el-button>
          <!-- <el-button type="primary" plain>主要按钮</el-button> -->
          <el-button size="mini" type="info" @click="handleDelete(scope.row.rid)" round>设置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页-->
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
        :page-sizes="[2,4,7]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 增加-->
    <el-dialog title="增加角色" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="form.rname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色代号" :label-width="formLabelWidth">
          <el-input v-model="form.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改-->
    <el-dialog title="修改角色" :visible.sync="dialogUpdaVisible">
      <el-form :model="form">
        <el-form-item label="编号" :label-width="formLabelWidth">
          {{form.rid}}
        </el-form-item>
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="form.rname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="代号" :label-width="formLabelWidth">
          <el-input v-model="form.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUpdaVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRole()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 赋权-->
    <el-drawer title="角色赋权" :before-close="handleClose" :visible.sync="dialog" direction="rtl"
      custom-class="demo-drawer" ref="drawer">
      <div class="demo-drawer__content">
        <el-tree :data="data.tree"  style="height: 480px;overflow-y: scroll;"  show-checkbox node-key="mid" default-expand-all highlight-current
          :default-checked-keys="data.mids" :props="defaultProps" @check-change="changeStrictly()"
          :check-strictly="boolIs" ref="tree">
        </el-tree>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm" round>取 消</el-button>
          <el-button type="primary" @click="$refs.drawer.closeDrawer()" :loading="loading" round>
            {{ loading ? '提交中 ...' : '确 定' }}
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import {
    mapState
  } from "vuex"
  export default {
    name: 'menus',
    inject:['reload'],
    data() {
      return {
        input: '',
        dialogFormVisible: false,
        dialogUpdaVisible: false,
        dialogRolesVisible: false,
        formLabelWidth: '90px',
        boolIs: true,
        pageNum: 1,
        pageSize: 7,
        total: 0,
        tableData: [],
        rid: 0,
        multipleSelection: [],
        form: {
          rid: '',
          rname: '',
          code: '',
          description: ''
        },
        table: false,
        dialog: false,
        loading: false,
        formLabelWidths: '80px',
        timer: null,
        data: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      }
    },
    methods: {
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
          this.multipleSelection = [];
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = [];
        for (var i = 0; i < val.length; i++) {
          this.multipleSelection.push(val[i].rid)
        }
      },
      tableRowClassName({
        row,
        rowIndex
      }) {
        if (rowIndex % 2 == 0) {
          return 'success-row';
        } else {
          return 'warning-row';
        }
        return '';
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.searchRole(this.pageNum, this.pageSize);
      },
      handleCurrentChange(val) {
        this.pageNum = val;
        this.searchRole(this.pageNum, this.pageSize);

      },
      addMenu() {
        this.dialogFormVisible = true;
      },
      /* 修改*/
      handleEdit(data) {
        this.form.rid = data.rid;
        this.form.rname = data.rname;
        this.form.code = data.code;
        this.form.description = data.description;

        this.dialogUpdaVisible = true;
      },
      handleClose(done) {
        if (this.loading) {
          return;
        }
        this.$confirm('确定要提交表单吗？')
          .then(_ => {
            this.loading = true;
            this.timer = setTimeout(() => {
              done();
              var rad = ''
              var ridsa = this.$refs.tree.getCheckedKeys().join(',') // 获取当前的选中的数据[数组] -id, 把数组转换成字符串
              var ridsb = this.$refs.tree.getCheckedNodes() // 获取当前的选中的数据{对象}
              ridsb.forEach(ids => { //获取选中的所有的父级id
                if (ids.pid != null) {
                  rad += ',' + ids.pid
                }
              })
              rad = rad.substr(1) // 删除字符串前面的','
              var rids = rad + ',' + ridsa
              var arr = rids.split(',') //  把字符串转换成数组
              arr = [...new Set(arr)]; // 数组去重
              rids = arr.join(',') // 把数组转换成字符串
              console.log(rids);
              var data = new URLSearchParams();
              data.append("rid", this.rid);
              data.append("mids", rids);
              this.$http.post('system/role/setRoleMenu', data).then(res => {
                if (res.state = 200) {
                  console.log("设置成功")
                  var id = this.user.rid;
                  if (this.rid == id) {
                    this.reload();
                    this.$router.push('/main/menus');
                  }
                }
              }).catch(err => {
                console.log(err);
              })
              this.boolIs = true;
              setTimeout(() => {
                this.loading = false;
              }, 100);
            }, 500);
          })
          .catch(_ => {});



      },
      cancelForm() {
        this.loading = false;
        this.dialog = false;
        clearTimeout(this.timer);
      },
      handleDelete(rid) {
        this.$http.post('system/menu/roleTree?rid=' + rid).then(res => {
          this.data = res.data;
        }).catch(err => {
          console.log(err)
        })
        this.rid = rid;
        this.dialog = true;
      },
      searchRole(pageNum, pageSzie) {
        var data = new URLSearchParams();
        data.append("pageNum", pageNum);
        data.append("pageSize", pageSzie);
        this.$http.post('system/role/findByPage', data).then(res => {
          if (res.data.rows) {
            console.log(res);
            this.pageNum = res.data.pageNum;
            this.pageSize = res.data.pageSize;
            this.tableData = res.data.rows;
            this.total = res.data.total;
          }
        }).catch(err => {
          console.log(err);
        })
      },
      addRole() {
        this.dialogFormVisible = false;
        var data = this.form;
        this.$http.post("system/role/addRole", this.$qs.stringify(data)).then(res => {
          if (res.state = 200) {
            this.$message({
              message: '添加成功',
              type: 'success'
            });
            this.form.rid = '';
            this.form.rname = '';
            this.form.code = '';
            this.form.description = '';
            this.searchRole(this.pageNum, this.pageSize);
          }
        }).catch(err => {
          console.log(err);
        })
      },
      updateRole() {
        this.dialogUpdaVisible = false
        var data = this.form;
        this.$http.post("system/role/updateRole", this.$qs.stringify(data)).then(res => {
          if (res.state = 200) {
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.form.rid = '';
            this.form.rname = '';
            this.form.code = '';
            this.form.description = '';
            this.searchRole(this.pageNum, this.pageSize);
          }
        }).catch(err => {
          console.log(err)
        })

      },
      batchDelMenus() {
        var rids = this.multipleSelection;
        if (rids.length > 0) {
          if (confirm('确定删除?')) {
            var data = new URLSearchParams();
            data.append("rids", rids);
            this.$http.post('system/role/batchDelRole', data).then(res => {
              if (res.state = 200) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.searchRole(this.pageNum, this.pageSize);
              }
            }).catch(err => {
              console.log(err);
            })
          }
        } else {
          alert('请选择要删除的信息');
        }
      },
      changeStrictly() {
        this.boolIs = false;
      }
    },
    computed: {
      tables() {
        var val = this.input;
        return this.tableData.filter(data => {
          return data.rname.indexOf(val) != -1;
        })
      },
      ...mapState(['user'])
    },
    mounted() {
      this.searchRole(this.pageNum, this.pageSize);
      /* console.log(this.user.rid+"dsadsa") */
    }
  }
</script>

<style>
  .el-input {
    width: 85%;
  }

  .block {
    margin-top: 8px;
  }

  .el-pagination {
    text-align: center;
  }

  .el-table .warning-row {
    background: white;
  }

  .el-table .success-row {
    background: whitesmoke;
  }

  #roles {
    line-height: 0px;

    margin-top: 2sspx;
    padding: 13px;
  }

  .el-table {

    margin-top: 10px;
  }

  .el-tree {
    padding-left: 10px;
    background: whitesmoke;
  }

  .demo-drawer__footer {
    margin-left: 20px;
    margin-top: 15px;
  }
</style>
